﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Globalization;
using System.IO;
using System.Linq;
using System.ServiceModel.Channels;
using System.Web;
using System.Web.UI.WebControls;
using AjaxControlToolkit;
using FreeTextBoxControls;
using NetDon.OA.Business;
using NetDon.OA.Data.CollectionClasses;
using NetDon.OA.Interface;
using NetDon.OA.Interface.Admin;
using NetDon.OA.Interface.Configuration;
using NetDon.OA.Interface.File;
using NetDon.Utilities;

namespace NetDon.OA.Portal
{

    public static class ControlHelper
    {
        public static bool GetImageFormat(string contentType, out System.Drawing.Imaging.ImageFormat imageFormat)
        {
            switch (contentType)
            {
                case "image/pjpeg":
                case "image/jpeg":
                    imageFormat = System.Drawing.Imaging.ImageFormat.Jpeg;
                    return true;
                case "image/gif":
                    imageFormat = System.Drawing.Imaging.ImageFormat.Gif;
                    return true;
                case "image/bmp":
                    imageFormat = System.Drawing.Imaging.ImageFormat.Bmp;
                    return true;
                case "image/tiff":
                    imageFormat = System.Drawing.Imaging.ImageFormat.Tiff;
                    return true;
                case "image/x-icon":
                    imageFormat = System.Drawing.Imaging.ImageFormat.Icon;
                    return true;
                case "image/x-png":
                    imageFormat = System.Drawing.Imaging.ImageFormat.Png;
                    return true;
                case "image/x-emf":
                    imageFormat = System.Drawing.Imaging.ImageFormat.Emf;
                    return true;
                case "image/x-exif":
                    imageFormat = System.Drawing.Imaging.ImageFormat.Exif;
                    return true;
                case "image/x-wmf":
                    imageFormat = System.Drawing.Imaging.ImageFormat.Wmf;
                    return true;
            }
            imageFormat = System.Drawing.Imaging.ImageFormat.MemoryBmp;
            return false;
        }

        public static string SaveReportFile(byte[] fileContent)
        {
            string fileName = Guid.NewGuid() + ".rpt";
            FileRepository.GetRepository(FileRepositoryNames.Report).WriteAllBytes(fileName, fileContent);
            return fileName;
        }

        //public static string SaveDocumentFile(HttpPostedFile file)
        //{
        //    string fileName = null;
        //    fileName = Guid.NewGuid() + FileUtilities.GetFileSystemInfo(file.FileName).Extension;
        //    FileRepository.GetRepository(FileRepositoryNames.Document).WriteAllBytes(fileName, FileUtilities.ReadAllBytes(file.InputStream));
        //    return fileName;
        //}

        public static string SaveFile(byte[] fileContent, string postfix)
        {
            string date = DateTime.Today.ToString("yyyyMMdd");
            var fileName = date + "/" + Guid.NewGuid() + postfix;
            FileRepository.GetRepository(FileRepositoryNames.Document).WriteAllBytes(fileName, fileContent);
            return fileName;
        }
        public static string SaveImageFile(byte[] fileContent, string extention)
        {
            string date = DateTime.Today.ToString("yyyyMMdd");
            var fileName = date + "/" + Guid.NewGuid() + extention;
            FileRepository.GetRepository(FileRepositoryNames.Image).WriteAllBytes(fileName, fileContent);
            return fileName;
        }

        public static bool SupportedImageFormat(string contentType)
        {
            return string.Compare(contentType, "image/pjpeg", true) == 0 ||
                   string.Compare(contentType, "image/jpeg", true) == 0 ||
                   string.Compare(contentType, "image/gif", true) == 0 ||
                   string.Compare(contentType, "image/bmp", true) == 0 ||
                   string.Compare(contentType, "image/x-png", true) == 0;
        }

        public static void SetMaskedEditDateFormat(MaskedEditExtender extender)
        {
            string format = SystemConfiguration.DateFormat;
            extender.ClearTextOnInvalid = true;
            var placeHolders = new[] { '-', '/', '.' };
            foreach (var c in placeHolders)
            {
                if (format.IndexOf(c) != -1)
                {
                    var array = format.ToLowerInvariant().Split(c);
                    var cultureDateFormat = string.Empty;
                    var mask = new string[array.Length];
                    for (int i = 0; i < array.Length; i++)
                    {
                        string part = array[i];
                        if (part == "yyyy" || part == "yy")
                        {
                            cultureDateFormat += "Y";
                        }
                        if (part == "mm" || part == "m")
                        {
                            cultureDateFormat += "M";
                        }
                        if (part == "dd" || part == "d")
                        {
                            cultureDateFormat += "D";
                        }

                        if (part == "yyyy")
                        {
                            mask[i] = "9999";
                        }
                        if (part == "yy" || part == "mm" || part == "m" || part == "dd" || part == "d")
                        {
                            mask[i] = "99";
                        }
                    }
                    extender.CultureName = CultureInfo.CurrentUICulture.Name;
                    extender.CultureDateFormat = cultureDateFormat;
                    extender.CultureDatePlaceholder = c.ToString();
                    extender.Mask = string.Join(c.ToString(), mask);
                    extender.MaskType = MaskedEditType.Date;
                    extender.Century = DateTime.Today.Year / 100 * 100;
                    break;
                }
            }
        }

        public static void SetFreeTextBoxEditor(FreeTextBox freeTextBox)
        {
            freeTextBox.FontSizesMenuList = new[] { "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20" };
            freeTextBox.FontSizesMenuNames = new[] { "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20" };
        }

        #region 从Excel读取数据
        public static DataTable GetDataFromExcel(FileUpload postFile, ref string errorMsg)
        {
            return GetDataFromExcel("Sheet1", postFile, ref errorMsg);
        }

        /// <summary>
        ///  从Excel读取数据
        /// </summary>
        /// <param name="strFileName">文件名称</param>
        /// <param name="strFileName">Sheet名称</param>
        /// <returns></returns>
        public static DataTable GetDataFromExcel(string strSheetName, FileUpload postFile, ref string errorMsg)
        {
            if (String.IsNullOrEmpty(postFile.FileName))
            {
                errorMsg = "";
                return null;
            }
            if (!postFile.FileName.ToUpper().EndsWith(".XLS"))
            {
                errorMsg = "";
                return null;
            }

           var fileName = postFile.FileName;
            var postfix = Path.GetExtension(fileName);
            fileName = SaveFile(postFile.FileBytes, postfix);

            //var fileName = SaveDocumentFile(postFile);
            fileName = Path.Combine(FileRepository.GetRepository(FileRepositoryNames.Document).Path, fileName);
            string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
                    "Data Source=" + fileName + ";" +
                     "Extended Properties='Excel 8.0;IMEX=1'";
            OleDbConnection objConn = new OleDbConnection(strConn);
            objConn.Open();
            DataTable dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            OleDbDataAdapter ExcelDA = new OleDbDataAdapter(string.Format("SELECT * FROM [{0}]", dt.Rows[0]["TABLE_NAME"].ToString()), strConn);
            DataSet ExcelDs = new DataSet();
            try
            {
                ExcelDA.Fill(ExcelDs, "ExcelInfo");
            }
            catch (Exception ex)
            {
                errorMsg = ex.InnerException.Message;
                return null;
            }
            finally
            {
                objConn.Close();
                File.Delete(fileName);
            }
            return ExcelDs.Tables[0];
        }
        #endregion

        /// <summary>
        /// 绑定dropdownlist，
        /// </summary>
        /// <param name="objList"></param>
        /// <param name="strSelectedValue"></param>
        public static void SetDropListValue(DropDownList objList, string strSelectedValue)
        {
            objList.ClearSelection();
            var item = objList.Items.FindByValue(strSelectedValue);
            if (item != null)
            {
                item.Selected = true;
            }
        }


        public static void BindUserRole(ListControl control, ListEmptyType emptyType)
        {
            control.Items.Clear();
            RoleCollection collection = new RoleCollection();
            collection.GetMulti(null);
            control.DataTextField = "RoleName";
            control.DataValueField = "RoleID";
            control.DataSource = collection;
            control.DataBind();
        }


        public static string GetCompanyName(Guid companyId)
        {
            var service = ServiceContainer.GetService<ICompanyService>();
            var data = service.GetCompany(companyId);
            if (data != null)
                return data.CompanyName;
            return null;
        }

        public static string GetDepartmentName(Guid departmentId)
        {
            var service = ServiceContainer.GetService<IDepartmentService>();
            var data = service.GetDepartment(departmentId);
            if (data != null)
                return data.DepartmentName;
            return null;
        }
    }
}


